<template>
  <div class="trading-app">
    <heard class="box-shadow"
    @listenPiceChange="handlePiceChange"
    :rexTableRows="rexTableRows" />
    <div class="trading-center flex fontx">
      <div class="tcen-cen">
        <div class="cen-top flex">
          <center-top />
        </div>
        <div class="cen-bottom box-shadow">
          <center-bottom
          @listenWalletLogin="handleWalletLogin"
          @listenWalletPermission="handleWalletPermission"
          @listenCenterBottom="handleCenterBottom"
          :rexTableRows="rexTableRows"
          :rexBalance="rexBalance"
          :cpunetPrice="cpunetPrice"
          :scatter="scatter"
          :eosBalance="eosBalance"
          :symbolScience="symbolScience"
          :fundBalance="fundBalance"
          :canBuyRexNum="canBuyRexNum" />
        </div>
      </div>

      <div class="tcen-right">
        <div class="top-right box-shadow mb">
          <vue-nav />
          <vue-table />
        </div>
        <!-- 介绍说明 -->
        <div class="rbottom box-shadow mb">
          <right-bottom/>
        </div>
        <!-- 关键数据 -->
        <div class="rcenter box-shadow">
          <right-center :rexTableRows="rexTableRows"/>
        </div>
      </div>
    </div>
    <div class="trading-bottom">
      <bottom
      :scatter="scatter"
      :eosBalance="eosBalance"
      :fundBalance="fundBalance"
      :symbolScience="symbolScience"
      :refreshOrder="refreshOrder"/>
    </div>

     <!-- 订单成交详情 -->
    <el-dialog
      class="orderDetail"
      :show-close='true'
      :close-on-click-modal="false"
      :visible.sync="orderDetailVisible"
      width="900px">
      <success-detail
      :order-detail-id="orderDetailId"
      @listenDetailClose="orderDetailVisible=false"/>
    </el-dialog>

    <!-- ram钱包扫码登录不能交易提示弹窗 -->
    <el-dialog
      class="ramTipBox"
      :close-on-click-modal="false"
      :visible.sync="cannotExchangeVisible"
      :show-close="false"
      width="680px">
      <div class="ramTip">
        <div class="tip">{{$t('jy.ramTipCaption')}}</div>
        <div class="tip">{{$t('jy.ramTip1', {type: 'REX'})}}</div>
        <div class="tip">{{$t('jy.ramTip2', {type: 'REX'})}}</div>
        <div class="tip">{{$t('jy.ramTip3')}}</div>
        <div class="tip" style="margin-top: 4px;">
          <el-button class="btn" type="primary" @click="handleCloseTip">{{$t('jy.ramTipBtn')}}</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import moment from 'moment';
import { EosModel } from '@/utils/eos';
import { toFixed } from '@/utils/validate';
import vueNav from '@/components/VueNav';
import vueTable from '@/components/VueTable';
import Heard from './components/Heard';
import RightCenter from './components/RightCenter';
import RightBottom from './components/RightBottom';
import Bottom from './components/Bottom';
import CenterBottom from './components/CenterBottom';
import CenterTop from './components/CenterTop';
import SuccessDetail from './components/SuccessDetail';

export default {
  name: 'rex-center',
  data() {
    return {
      scatter: {},
      orderDetailId: '',
      orderDetailVisible: false,
      refreshOrder: false,
      cannotExchangeVisible: false, // ram不能交易弹窗
      rexDetail: true, // rex简介显示
      rexTableRows: {
        timer: 0,
      },
      rexBalance: null,
      eosBalance: '0.0000 EOS',
      fundBalance: 0, // 储备金余额
      timerRexTableRows: null,
      timerBlance: null,
      canBuyRexNum: null,
      symbolScience: 'EOS',
      cpunetPrice: 0,
    };
  },
  components: {
    Heard,
    RightCenter,
    Bottom,
    CenterBottom,
    CenterTop,
    SuccessDetail,
    vueTable,
    vueNav,
    RightBottom
  },
  watch: {
    // 余额获取
    '$store.state.app.scatter.identity': {
      handler: function listen(val) {
        this.scatter = this.$store.state.app.scatter;
        if (val) {
          this.handleBlanceIvit();
        }
      },
      deep: true,
    },
  },
  created() {
    document.title = this.$t(`rout.${this.$route.meta.title}`);
  },
  mounted() {
    this.scatter = this.$store.state.app.scatter;
    this.handleExchangeScience();
    this.handleGetRexTableRow();
    this.handleBlanceIvit();
  },
  beforeDestroy() {
    if (this.timerBlance) {
      clearTimeout(this.timerBlance);
    }
    if (this.timerRexTableRows) {
      clearTimeout(this.timerRexTableRows);
    }
  },
  methods: {
    // 余额获取
    handleBlanceIvit() {
      const scatter = this.scatter;
      if (scatter && scatter.identity && scatter.chain === 'eos') {
        // 获取储备金余额
        EosModel.getRexFundBlance((row) => {
          if (!row.rows.length) {
            this.fundBalance = 0;
          } else {
            this.fundBalance = parseFloat(row.rows[0].balance, 0);
          }
        })
        EosModel.getCurrencyBalance(this.symbolScience, 'eosio.token', (result) => {
          if (!result.length) {
            this.eosBalance = '0.0000 EOS';
          } else {
            this.eosBalance = result[0];
          }
        });
        EosModel.getRexBlance((result) => {
          const row = result.rows;
          if (row && !row.length) {
            this.rexBalance = '0.0000 REX';
            this.canBuyRexNum = '0.0000';
          } else {
            this.rexBalance = row[0].rex_balance;
            const rexMaturities = row[0].rex_maturities;
            this.canBuyRexNum = 0;
            this.rexHistroyList = [];
            rexMaturities.forEach((v) => {
              const zone = moment().zone() / 60; // 时区
              const jsTime = moment(v.first).add(0 - zone, 'hours').format('YYYY/MM/DD HH:mm:ss'); // 解锁时间
              const jsBdTime = new Date(jsTime).getTime();
              const bdTime = new Date().getTime();
              const flg = bdTime - jsBdTime >= 0;
              if (flg) {
                this.canBuyRexNum += Number(v.second);
              }
              const item = {
                jsTime,
                flg, // true, 可卖出
                second: v.second,
              };
              this.rexHistroyList.push(item)
            });
            this.canBuyRexNum += Number(row[0].matured_rex);
            this.canBuyRexNum = toFixed(this.canBuyRexNum / 10000, 4);
          }
        });
      }
      if (this.timerBlance) {
        clearTimeout(this.timerBlance);
      }
      this.timerBlance = setTimeout(this.handleBlanceIvit, 5000);
    },
    // 关闭ram弹窗
    handleCloseTip() {
      this.cannotExchangeVisible = false;
    },
    handleWalletLogin() {
      this.$emit('listenWalletLogin', true);
    },
    /**
     * 钱包授权
     */
    handleWalletPermission() {
      const checkWallet = localStorage.getItem('checkWallet');
      if (checkWallet && !Number(checkWallet)) {
        this.$emit('listenWalletPermission', true);
        return;
      }
      this.$emit('listenWalletLogin', true);
    },
    // 监听交易中心的变化
    handleCenterBottom(key) {
      if (key === 'refresh') {
        this.refreshOrder = !this.refreshOrder;
      }
    },
    // 获取rex全网信息
    handleGetRexTableRow() {
      EosModel.getRexTableRows((row) => {
        if (row.code) return;
        // namebid_proceeds: "0.0000 EOS"
        // total_lendable: "56668081.1690 EOS"   总量
        // total_lent: "1372018.5243 EOS"   已出租
        // total_rent: "20824.1210 EOS"   -20000，租金
        // total_rex: "566563921265.5349 REX"  总量
        // total_unlent: "55296062.6447 EOS"   剩余可出租
        // version: 0
        this.rexTableRows = row;
        // 年化收益率 计算
        const since = Date.now() - moment('2019-05-01 20:00:00').format('x');
        const n = ((parseFloat(row.total_lendable, 0) / parseFloat(row.total_rex, 0)) - 0.0001) / 0.0001;
        const apr = parseFloat((n / since) * 365 * 24 * 3600 * 1000 * 100).toFixed(2);
        this.rexTableRows.apr = apr;
        this.rexTableRows.timer = new Date().getTime();
        if (this.timerRexTableRows) {
          clearTimeout(this.timerRexTableRows);
        }
        this.timerRexTableRows = setTimeout(this.handleGetRexTableRow, 5000);
      })
    },
    handlePiceChange(price) {
      this.cpunetPrice = price || 3103.9923;
    },
    // 交易环境
    handleExchangeScience() {
      const env = process.env.NODE_ENV;
      let Science = 'EOS';
      switch (env) {
        case 'development':
          Science = 'SYS'
          break;
        case 'production':
          Science = 'EOS';
          break;
        default:
          Science = 'EOS';
          break;
      }
      this.symbolScience = Science;
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/assets/css/variables.scss";

$-cent-height: 1000px; // 总高度
$-rtop-height: 218px;
$-rcenter-height: 330px;
$-rcenterTop: 464px; // 上半部分
$-rcenter-top: 250px; // 关键数据高度

.trading-app {
  max-width: 1260px;
  margin: 0 auto;
  padding: 10px 0 30px 0;
}
.trading-center {
  padding: 0;
  margin-top: 10px;
  height: $-cent-height;

  .tcen-left {
    min-width: 278px;
    width: 278px;
    max-width: 278px;
    height: $-cent-height;
  }
  // 左边信息
  .tcen-cen {
    margin: 0 10px 0 0;
    flex: 1;

    .cen-top {
      margin-bottom: 10px;
    }
    .cen-top-left {
      margin-right: 10px;
      width: 287px;
      max-width: 287px;
      min-width: 287px;
    }
    .cen-top, .cen-top-left {
      // height: ($-cent-height*6) / 11 - 5;
      height: $-rcenterTop;
    }
    .cen-bottom {
      // height: ($-cent-height*5) / 11 - 5;
      height: $-cent-height - $-rcenterTop - 10;
    }
  }
  // 右边信息
  .tcen-right {
    width: 287px;
    min-width: 287px;

    .rtop {
      height: $-rtop-height
    }
    .top-right {
      width: 287px;
      min-width: 287px;
      height: $-rcenterTop;
    }
    .rcenter {
      height: $-rcenter-top;
    }
    .rbottom {
      height: $-cent-height - $-rcenterTop - $-rcenter-top - 20;
    }
  }

  .cen-top {
    .tcen-right {
      margin-left: 10px;
    }

    & .rtop, .tradcen{
      height: ($-cent-height*6) / 11 - 5;
    }

    .tradcen {
      max-width: 675px;
      flex: 1;
    }
    background: none !important;
  }
}

.box-shadow {
  border: 1px solid #eee;
  box-shadow: none;
}

.ramTipBox {
  font-size: 14px;
  margin-top: 18vh;
  .tip {
    margin-bottom: 20px;
    color: #101010;
  }
  .tip:first-child {
    color: #FF9800;
  }
  .btn {
    width: 200px;
    margin-top: 20px;
  }
}
/deep/ .el-dialog__header {
  padding: 8px;
}
.plr30 {
  padding: 0 30px;
}

.theme-278EDA {
  .trading-app .table-sty{
    background: #fff;
  }
  .trading-app {
    // background: #fff;
  }
}


.theme-1B1D27 {
  .btboxbg {
    background: $-topcolor2;
  }
  .box-shadow {
    border: 1px solid rgba(0, 0, 0, .1);
    box-shadow: none;
    background: $-topcolor;
  }
  .tradcen {
    width: 616px;
    background: $-topcolor;
  }
  .topcolor {
    background: $-topcolor3;
  }
  .trading-bottom {
  }

  .trading-center {
    .cen-top{
    }
  }
  .ramTip {
    .tip {
      color: rgba(255, 255, 255, .75);
    }
  }
}

.btbox {
  padding: 5px;
}

.orderDetail {
  /deep/ .el-dialog {
    margin-top: 25vh !important;
  }
}
.ramTip {
  text-align: center;
}
</style>

